package com.ly.controller;

import com.ly.common.Result;
import com.ly.common.StatusEnum;
import com.ly.common.TokenHandler;
import com.ly.dao.IconDao;
import com.ly.dao.MenuDao;
import com.ly.dao.RoleMenuDao;
import com.ly.dao.RolesDao;
import com.ly.entity.Menu;
import com.ly.entity.Roles;
import com.ly.entity.User;
import com.ly.exp.ServiceException;
import com.ly.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/menu")
@Api(tags = "菜单模块")
public class MenuController {
    @Resource
    public MenuDao menuDao;
    @Resource
    public MenuService menuService;
    @Resource
    public IconDao iconDao;
    @Resource
    public RolesDao rolesDao;
    @Resource
    public RoleMenuDao roleMenuDao;

    @PostMapping("/addMenu")
    @ApiOperation(value = "新增菜单")
    public Result<?> addMenu(@RequestBody @Validated Menu menu){
        menuService.addMenu(menu);
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @PostMapping("/updateMenu")
    @ApiOperation(value = "新增菜单")
    public Result<?> updateMenu(@RequestBody @Validated Menu menu){
        if(menu.getId() == null){
            throw new ServiceException(StatusEnum.ERROR.getCode(),"请选择菜单");
        }
        menuDao.updateById(menu);
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @DeleteMapping("/delMenu")
    @ApiOperation(value = "新增菜单")
    public Result<?> delMenu(@RequestParam Integer menuId){
        menuService.delMenu(menuId);
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @PostMapping("/menuList")
    @ApiOperation(value = "菜单列表")
    public Result<?> menuList(@RequestBody @Validated Menu menu){
        List<Menu> menuList = menuService.menuList();
        return  new Result<>(menuList,StatusEnum.SUCCESS);
    }

    @GetMapping("/parentMenuList")
    @ApiOperation(value = "获取父菜单")
    public Result<?> parentMenuList(@RequestBody @Validated Menu menu){
        List<Menu> menuList = menuDao.queryParentMenu();
        return  new Result<>(menuList,StatusEnum.SUCCESS);
    }

    @GetMapping("/iconList")
    @ApiOperation(value = "获取父菜单")
    public Result<?> iconList(){
        return  new Result<>(iconDao.queryAll(),StatusEnum.SUCCESS);
    }

    @GetMapping("/menuChildrenList")
    @ApiOperation(value = "获取所有含有跳转路径的菜单")
    public Result<?> menuChildrenList(@RequestParam(required = false)  String menuName){
        User userInfo = TokenHandler.getUserInfo();
        Roles roles = rolesDao.selectByRoleName(userInfo.getRole());
        List<Integer> menuIds = roleMenuDao.selectByRoleId(roles.getId());
        List<Menu> menuChildrenList = menuDao.menuChildrenList(menuName, menuIds);
        return  new Result<>(menuChildrenList,StatusEnum.SUCCESS);
    }
}
